import {storeBindingsBehavior} from "mobx-miniprogram-bindings";
import base from "@src/store/base";
import mall from "@src/store/mall";
import {getNearStore} from "@mall/api/store";
import router from "@src/router";
import {batchDeleteItem} from "@mall/api/shopCart";

const {getShopCartList} = require("@mall/api/shopCart");
Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: base,
    fields: ['businessName', 'businessLogo', 'navBarHeight', 'themeTitleColor', 'themeColor'],
  }, {
    store: mall,
    fields: ['curLocation', 'storeId'],
    actions: ['initLocation', 'setAddress', 'setStoreId']
  }],
  properties: {},
  data: {
    loading: true,
    defaultStoreId: 0,
    cartList: [],
    firstShow: true,
    invalidItems: [],
  },
  methods: {
    onLoad() {
    },
    onShow() {
      if (this.data.firstShow) {
        this.setData({firstShow: false})
        return;
      }
      if (this.data.storeId) {
        this.fetchData();
      }
    },
    onLogin() {
      this.updateStoreBindings();
      if (this.data.storeId) {
        this.fetchData();
        return;
      }
      if (!this.data.curLocation) {
        // 先拉取一个默认门店
        this.fetchDefaultStore().then(() => {
          this.fetchData();
        });
      }
      // 定位, 并刷新购物车
      this.initLocation().then(res => {
        let params = {latitude: res.latitude, longitude: res.longitude}
        this.fetchNearStore(params).then(res => {
          this.fetchData();
        })
      }).catch(error => {
        this.fetchNearStore({}).then(res => {
          this.fetchData();
        })
      });
    },
    fetchData() {
      let storeId = this.data.storeId;
      if (storeId == null) {
        storeId = this.data.defaultStoreId;
      }
      let data = {
        storeId: storeId,
        cartType: 0
      }
      getShopCartList(data).then(res => {
        console.info(res)
        let cartList = res.data;
        let invalidItems = [];
        for (let i = 0; i < cartList.length; i++) {
          let cart = cartList[i];
          if (cart.invalidItems && cart.invalidItems.length > 0) {
            invalidItems = invalidItems.concat(cart.invalidItems)
          }
        }
        this.setData({cartList, invalidItems, loading: false})
      })
    },
    updataFetchData:function (){
      this.fetchData()
    },
    onPullDownRefresh: function () {
      if (this.data.storeId) {
        this.fetchData();
      }
      wx.stopPullDownRefresh();
    },
    fetchNearStore(params) {
      return getNearStore(params).then(res => {
        this.setStoreId(res.data.storeId)
        this.updateStoreBindings();
        return res;
      })
    },
    fetchDefaultStore() {
      return getNearStore({}).then(res => {
        this.setData({defaultStoreId: res.data.storeId})
        return res;
      })
    },
    goGoodsList() {
      router.push({name: "mall/goods-list", params: {storeId: this.data.storeId}})
    },
    handleUpdate() {
      this.fetchData();
    },
    handleToServiceStores(e) {
      let deliveryType = e.detail.deliveryType
      router.push(
          {
            'name': 'mall/service-stores',
            params: {deliveryType: deliveryType},
            events: {
              'changeStore': (data) => {
                this.setStoreId(data.store.storeId)
                this.updateStoreBindings();
                this.setData({loading: true, invalidItems: []})
                this.fetchData();
                setTimeout(() => {
                  wx.showToast({title: "已切换到 " + data.store.name, icon: "none", duration: 1500})
                }, 500)
              }
            }
          });
    },
    handleClearInvalidItems() {
      if (this.data.invalidItems.length > 0) {
        wx.showModal({
          title: "温馨提示", content: "是否清除失效商品?",
          showCancel: true,
          success: (res) => {
            if (res.confirm) {
              let cartItemDel = [];
              this.data.invalidItems.forEach(item => {
                let temp = {
                  cartItemId: item.cartItemId,
                  goodsId: item.goodsId,
                  skuId: item.skuId,
                  storeId: item.storeId,
                }
                cartItemDel.push(temp);
              })
              batchDeleteItem(cartItemDel).then(res => {
                this.setData({invalidItems: []})
                this.fetchData()
              })
            }
          }
        });
      }
    }
  }
});
